import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { login, getMenu } from "../api/api";
import Cache from "../utils/cache/cache";
import lists from "../router/modules/home";
import router from "../router/index";

export const useUser = defineStore('user', {
    state: () => ({
        token: '',
        uid: 0,
        menulist: []
    }),
    actions: {
        async loginAction(ruleForm: any) {
            let res = await login(ruleForm);
            if (res.data.code == 1) {
                this.token = res.data.token
                this.uid = res.data.uid
                Cache.setCache("userinfo", {
                    token: res.data.token,
                    uid: res.data.uid,
                });
            }

            // 获取菜单
            let { uid } = Cache.getCatch("userinfo");
            let result = await getMenu(uid)
            this.menulist = result.data.data
            this.addMenuFn()
        },
        addMenuFn() {
            for (let menu of this.menulist) {
                const route: any = lists.find((item) => item.path == menu.purl);
                router.addRoute("index", route);
            }
        }
    }
})